package com.qiniuyun.backai.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.qiniuyun.backai.common.PageResult;
import com.qiniuyun.backai.domain.po.Character;
import com.qiniuyun.backai.domain.vo.CharacterVO;
import com.qiniuyun.backai.mapper.CharacterMapper;
import com.qiniuyun.backai.service.ICharacterService;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.List;
import java.util.stream.Collectors;

/**
 *  角色服务实现类
 *  @author 王程楠
 *  @since  2025-09-23
 */
@Service
public class ICharacterServiceImpl extends ServiceImpl<CharacterMapper, Character> implements ICharacterService {

    @Override
    public PageResult<CharacterVO> pageCharacters(Integer page, Integer size) {
        // 创建分页对象
        // MyBatis-Plus页码从0开始
        Page<Character> pageParam = new Page<>(page, size);
        
        // 执行分页查询
        IPage<Character> pageResult = this.page(pageParam);
        
        // 转换为VO
        List<CharacterVO> voList = pageResult.getRecords().stream()
                .map(this::convertToVO)
                .collect(Collectors.toList());
        
        return new PageResult<>(voList, page, size, pageResult.getTotal());
    }

    @Override
    public CharacterVO getCharacterById(Long charId) {
        Character character = this.getById(charId);
        return character != null ? convertToVO(character) : null;
    }

    @Override
    public List<CharacterVO> searchCharacters(String keyword) {
        LambdaQueryWrapper<Character> queryWrapper = new LambdaQueryWrapper<>();
        
        if (StringUtils.hasText(keyword)) {
            queryWrapper.like(Character::getName, keyword)
                    .or()
                    .like(Character::getDescription, keyword);
        }
        
        List<Character> characters = this.list(queryWrapper);
        
        return characters.stream()
                .map(this::convertToVO)
                .collect(Collectors.toList());
    }

    /**
     * 将Character转换为CharacterVO
     */
    private CharacterVO convertToVO(Character character) {
        CharacterVO vo = new CharacterVO();
        vo.setCharId(character.getCharId());
        vo.setName(character.getName());
        vo.setDescription(character.getDescription());
        vo.setAvatarUrl(character.getAvatarUrl());
        vo.setBackgroundInfo(character.getBackgroundInfo());
        return vo;
    }
}